<template>
  <div class="category-list">
    <van-tabs
      v-model:active="activeCategory"
      :swipeable="true"
      :sticky="sticky"
      :offset-top="offsetTop"
      :background="background"
      @change="onChange"
    >
      <van-tab
        v-for="category in categories"
        :key="category.id"
        :title="category.name + (showCount ? ` (${category.count})` : '')"
        :name="category.id"
      />
    </van-tabs>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  categories: {
    type: Array,
    default: () => []
  },
  defaultActive: {
    type: [String, Number],
    default: ''
  },
  showCount: {
    type: Boolean,
    default: true
  },
  sticky: {
    type: Boolean,
    default: true
  },
  offsetTop: {
    type: Number,
    default: 0
  },
  background: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['change'])

const activeCategory = ref(props.defaultActive || (props.categories[0]?.id || ''))

// 监听默认值变化
watch(
  () => props.defaultActive,
  (newVal) => {
    if (newVal) {
      activeCategory.value = newVal
    }
  }
)

// 分类变化事件
const onChange = (name) => {
  const category = props.categories.find(item => item.id === name)
  emit('change', category)
}
</script>

<style lang="scss" scoped>
.category-list {
  width: 100%;
  
  :deep(.van-tabs__wrap) {
    height: 44px;
  }
  
  :deep(.van-tab) {
    flex: 0 0 auto;
    padding: 0 16px;
  }
  
  :deep(.van-tabs__line) {
    background-color: var(--primary-color);
  }
}
</style> 